import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
// 3. 注册
Vue.use(Vuex)
// 4. 实例化store对象
const store = new Vuex.Store({
    state: {
        goodsList:[]
    },
    mutations: {
        setGoodsList(state, newList) {
            state.goodsList=newList
        }
    },
    actions: {
        async asyncGetGoodsList(store) {
            const res = await axios({
                method: 'GET',
                url: 'https://www.escook.cn/api/cart'
              })
            store.commit('setGoodsList', res.data.list)
            console.log(res);
          }
    },
    getters: {
        allCount(state) {
            return state.goodsList.reduce((sum,obj) => {
                if (obj.goods_state == true) {
                    sum += obj.goods_count;
                }
                return sum;
             },0)
        },
        allPrice(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                  sum+=state.goods_count*state.goods_price
                }
                return sum
          },0)  
        }
    }
})
// 5. 导出store对象
export default store